package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.RegexUtils;

public class ChengjiangBbsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		String[] regex = {
				".*/tieba_show_[0-9]+.html",
		};
		return RegexUtils.matchAny(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta bbs = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		
		String url = urlMeta.getUrl();
		bbs.setUrl(url);
		String title = null;
		String content = null;
		String htmltxt = null;
		Long date = null;
		String commnetNum = null;
		String clickNum = null;
		String author = null;
		if (url.contains("tieba/../")) {
			url = url.replace("/tieba/../", "/");
			urlMeta = CrawlHTML.responseToURL(url);
			htmltxt = urlMeta.getHtml();
			
		}
			Document doc = Jsoup.parse(htmltxt);
			
			title = doc.select("div.post_title h2").text();
			content = HtmlCleaner.getContentHtml(url, doc.select("div.post_con"));
			date = DateUtils.matchDate(doc.select("span.r_time").text());
			Elements authorList = doc.select("div.username");
			if(authorList.size() > 0){
				author = authorList.get(0).text();
			}
					
		bbs.setTitle(title);
		bbs.setContent(content);
		bbs.setDate(date);
		
		/**
		 * 解析用于更新的地址
		 */
		bbs.setUpdateUrl(url);
		bbs.setClickNum(NumberUtils.parseInt(clickNum));
		bbs.setCommentNum(NumberUtils.parseInt(commnetNum));
		bbs.setAuthor(author);
		return bbs;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if (StringUtils.isNotBlank(updateUrl)){
				UrlMeta urlMeta = CrawlHTML.responseToURL(updateUrl);
				return parserHtml(urlMeta);
			}
			return null;
		}
		return null;
	}

	
	
	
}
